package com.unohacha.qqj.fzdr.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.qpg.superhttp.SuperHttp;
import com.qpg.superhttp.callback.SimpleCallBack;
import com.qpg.widget.common.ToastUtil;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.bean.BaseBean;
import com.unohacha.qqj.fzdr.bean.BooleanModel;
import com.unohacha.qqj.fzdr.bean.homebean.HomeOpenProvinceBean;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.view.MyGridView;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 发布结算
 */
public class PubSettlementActivity extends BaseActivity {
    private OptionsPickerView pvOptionsType;
    ArrayList<HomeOpenProvinceBean.DataEntity.CityEntity.ReaEntity> result;
    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.tv_select_day)
    TextView tvSelectDay;
    @BindView(R.id.tv_select_city)
    TextView tvSelectCity;
    @BindView(R.id.tv_pub_submit)
    TextView tvPubSubmit;
    @BindView(R.id.gv_sing_style)
    MyGridView gvSingStyle;
    ArrayList<String> days;
    HashMap<String,String> map;
    String day="1";
    StringBuilder sbCityList;
    private ArrayList<String> list;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pub_settlement;
    }

    @Override
    protected void initData() {
        super.initData();
        commonTitle.setText("发布结算");
        commonRightImage.setVisibility(View.GONE);
        map=(HashMap<String, String>) getIntent().getSerializableExtra("params");
        days=new ArrayList<>();
        days.add("1");
        days.add("3");
        days.add("7");
        days.add("10");
        tvSelectDay.setText("1天");
        pvOptionsType = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvSelectDay.setText(days.get(options1)+"天");
                day=days.get(options1);
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.BLUE)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        pvOptionsType.setPicker(days);
    }

    @OnClick({  R.id.common_back,R.id.tv_select_day,R.id.tv_select_city,R.id.tv_pub_submit})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.common_back:
                finish();
                break;
            case R.id.tv_select_day:
                pvOptionsType.show();
                break;
            case R.id.tv_select_city:
                final Intent intent=new Intent(PubSettlementActivity.this,PubSelectLocateActivity.class);
                startActivityForResult(intent,1006);
                break;
            case R.id.tv_pub_submit:

                if(sbCityList==null || sbCityList.toString().length()<2){
                    ToastUtil.showCustomToast("请选择地区");
                    return;
                }
                map.put("release_days",day);
                map.put("area_id",sbCityList.toString());
                Log.e("lists",map+"//");
                showLoading();
                SuperHttp.post("api/supplyinfo/supplyFile")
                        .addParams(map)
                        .request(new SimpleCallBack<BaseBean<HashMap<String,String>>>() {
                            @Override
                            public void onSuccess(BaseBean<HashMap<String,String>> data) {//10022018062709395158080
                                ToastUtil.showCustomToast(data.getMessage());
                                if(data.getCode()==1){
                                    supplyFilePay(data.getData().get("order"));
                                } else {
                                    ToastUtil.showCustomToast(data.getMessage());
                                }
                                hideLoading();
                            }

                            @Override
                            public void onFail(int errCode, String errMsg) {
                                ToastUtil.showCustomToast(errMsg);
                                hideLoading();
                            }
                        });
                break;
        }
    }

    /**
     * 支付预留接口
     * @param orderId
     */
    private void supplyFilePay(final String orderId) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", Prefer.getInstance().getToken());
        map.put("order", orderId);
        map.put("pay_type", "5");
        XUtil.Post(UrlConfig.SUPPLY_FILE_PAY, map, new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("===", result);
                try {
                    BooleanModel booleanModel = new BooleanModel().toBean(result);
                    if (booleanModel.getCode() == 1) {
                        Intent intent = new Intent(PubSettlementActivity.this, AfterPubMatchActivity.class);
                        intent.putExtra("orderId", orderId);
                        startActivity(intent);

                        finish();
                    } else {
                        ToastUtil.showCustomToast(booleanModel.getMsg());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            int num = 0;
            result =(ArrayList<HomeOpenProvinceBean.DataEntity.CityEntity.ReaEntity>)data.getExtras().getSerializable("cityInfo");//得到新Activity关闭后返回的数据
            list = (ArrayList<String>)data.getExtras().getSerializable("listCity");//得到选中城市的数据
            if(result==null){
                return;
            }
            sbCityList=new StringBuilder();
            sbCityList.append(",");

            for(int i=0;i<result.size();i++){
                if(result.get(i).isChecked()){
                    sbCityList.append(result.get(i).getId()+",");

                }
            }
            
            for (int i = 0; i < result.size(); i++) {
                if (result.get(i).isChecked()){
                    num ++;
                }
            }
            tvSelectCity.setText(list.size() + "个");
            final MyGridAdapter myGridAdapter = new MyGridAdapter();
            gvSingStyle.setAdapter(myGridAdapter);


            //gridView条目点击删除
            gvSingStyle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    list.remove(position);
                    myGridAdapter.notifyDataSetChanged();
                    tvSelectCity.setText(list.size() + "个");
                }
            });
        }

    }

    public class MyGridAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            MyViewHolder holder;
            if(convertView == null){
                convertView = LayoutInflater.from(PubSettlementActivity.this).inflate(R.layout.item_region_location_text,null);
                holder = new MyViewHolder();
                holder.tv = convertView.findViewById(R.id.item_region_tv);
                convertView.setTag(holder);
            }else{
                holder = (MyViewHolder) convertView.getTag();
            }
            holder.tv.setText(list.get(position));

            return convertView;
        }

        class MyViewHolder{
            TextView tv;
        }
    }
}
